﻿using CuteWallpaperDemo.Managers;
using CuteWallpaperDemo.Models;
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace CuteWallpaperDemo.Views
{
    /// <summary>
    /// NotifyWindow.xaml 的交互逻辑
    /// </summary>
    public partial class AlertWindow : NotifyWindowBase
    {
        public AlertWindow()
        {
            InitializeComponent();
            SetupAutoCloseTimer();
            this.Loaded += NotifyWindow_Loaded;
            this.SourceInitialized += OnSourceInitialized;
        }

        private void OnSourceInitialized(object? sender, EventArgs e)
        {
            SetPositionRelativeToOwner();
            EnterAnamitor();
        }

        private void EnterAnamitor()
        {
            // 设置初始位置
            var start = this.Top + this.ActualHeight;
            var end = this.Top;
            this.Top = start;

            MoveUpWindow(start, end);
        }



        private void NotifyWindow_Loaded(object sender, RoutedEventArgs e)
        {

        }

        /// <summary>
        /// 设置窗口位置
        /// </summary>
        protected override void SetPositionRelativeToOwner()
        {
            this.Width = cnt.ActualWidth + 30;
            this.Height = cnt.ActualHeight + 14;

            var owner = this.Owner;
            if (owner == null)
            {
                this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                return;
            }

            double ownerTop = CurrentTop;
            double ownerLeft = owner.Left;
            double ownerWidth = owner.ActualWidth;

            if (owner.WindowState == WindowState.Maximized)
            {
                ownerTop = 0;
                ownerLeft = 0;
            }

            // 计算新窗口的位置
            double newWindowTop = ownerTop + 50; // 新窗口顶部位置为拥有者窗口底部
            double newWindowLeft = ownerLeft + (ownerWidth - this.ActualWidth) / 2; // 新窗口左边位置为拥有者窗口中心

            // 设置新窗口的位置
            this.Top = newWindowTop;
            this.Left = newWindowLeft;
        }


        /// <summary>
        /// 定时自动关闭
        /// </summary>
        private void SetupAutoCloseTimer()
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new System.TimeSpan(0, 0, 0, 1, 500); // 设置为2秒
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        private void Timer_Tick(object? sender, System.EventArgs e)
        {
            // 停止计时器并关闭窗口
            var timer = sender as DispatcherTimer;
            if (timer != null)
            {
                timer.Stop();
            }
            this.Close();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            NotifyManager.Instance.RemoveAlert();

            base.OnClosing(e);
        }
    }
}
